<template>
  <div class="search-page">
    <!-- 顶部导航栏 -->
    <Navbar />

    <div class="container">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>搜索结果</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="content">
        <!-- 搜索条件 -->
        <div class="search-conditions">
          <div class="search-header">
            <h3>搜索 "{{ searchParams.goodsName }}"</h3>
            <span class="result-count">找到 {{ total }} 件相关商品</span>
          </div>

          <!-- 筛选条件 -->
          <div class="filters">
            <!-- 分类筛选 -->
            <div class="filter-item">
              <label>分类：</label>
              <div class="filter-options">
                <el-tag
                  :type="!searchParams.categoryId ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleCategoryChange(null)"
                >
                  全部
                </el-tag>
                <el-tag
                  v-for="category in categories"
                  :key="category.categoryId"
                  :type="searchParams.categoryId === category.categoryId ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleCategoryChange(category.categoryId)"
                >
                  {{ category.categoryName }}
                </el-tag>
              </div>
            </div>

            <!-- 价格筛选 -->
            <div class="filter-item">
              <label>价格：</label>
              <div class="price-filter">
                <el-input-number
                  v-model="priceRange.min"
                  :min="0"
                  :precision="2"
                  placeholder="最低价"
                  controls-position="right"
                  size="small"
                  style="width: 150px"
                />
                <span class="price-separator">-</span>
                <el-input-number
                  v-model="priceRange.max"
                  :min="0"
                  :precision="2"
                  placeholder="最高价"
                  controls-position="right"
                  size="small"
                  style="width: 150px"
                />
                <el-button type="primary" size="small" @click="handlePriceFilter">
                  确定
                </el-button>
                <el-button size="small" @click="handlePriceReset">
                  重置
                </el-button>
              </div>
            </div>

            <!-- 排序 -->
            <div class="filter-item">
              <label>排序：</label>
              <div class="filter-options">
                <el-tag
                  :type="sortBy === 'default' ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleSort('default')"
                >
                  默认
                </el-tag>
                <el-tag
                  :type="sortBy === 'sales' ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleSort('sales')"
                >
                  销量
                </el-tag>
                <el-tag
                  :type="sortBy === 'price-asc' ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleSort('price-asc')"
                >
                  价格升序
                </el-tag>
                <el-tag
                  :type="sortBy === 'price-desc' ? 'danger' : ''"
                  class="filter-tag"
                  @click="handleSort('price-desc')"
                >
                  价格降序
                </el-tag>
              </div>
            </div>
          </div>
        </div>

        <!-- 商品列表 -->
        <div class="goods-list" v-loading="loading">
          <el-empty 
            v-if="!loading && goodsList.length === 0" 
            description="没有找到相关商品"
            :image-size="200"
          >
            <el-button type="primary" @click="goToHome">返回首页</el-button>
          </el-empty>

          <div v-else class="goods-grid">
            <el-card
              v-for="goods in sortedGoodsList"
              :key="goods.id"
              class="goods-card"
              :body-style="{ padding: '0px' }"
              shadow="hover"
              @click="goToDetail(goods.id)"
            >
              <img :src="getImageUrl(goods.picture)" class="goods-image" />
              <div class="goods-info">
                <h3 class="goods-name">{{ goods.goodsName }}</h3>
                <div class="goods-stats">
                  <span class="stat-item">
                    <el-icon><ShoppingCart /></el-icon>
                    {{ goods.payNums }}
                  </span>
                  <span class="stat-item">
                    <el-icon><ChatDotRound /></el-icon>
                    {{ goods.commentNums }}
                  </span>
                </div>
                <div class="goods-footer">
                  <span class="goods-price">¥{{ goods.price }}</span>
                  <span class="goods-stock">库存: {{ goods.stock }}</span>
                </div>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 分页 -->
        <el-pagination
          v-if="total > 0"
          class="pagination"
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[12, 24, 36, 48]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="loadSearchResults"
          @current-change="loadSearchResults"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { searchGoods } from '@/api/search'
import { getAllCategories } from '@/api/category'
import { getFileUrl } from '@/api/file'
import { ElMessage } from 'element-plus'
import { ShoppingCart, ChatDotRound } from '@element-plus/icons-vue'
import Navbar from '@/components/Navbar.vue'

const route = useRoute()
const router = useRouter()

const loading = ref(false)
const goodsList = ref([])
const categories = ref([])
const pageNum = ref(1)
const pageSize = ref(12)
const total = ref(0)
const sortBy = ref('default')

const searchParams = ref({
  goodsName: '',
  categoryId: null,
  minPrice: null,
  maxPrice: null
})

const priceRange = ref({
  min: null,
  max: null
})

// 排序后的商品列表
const sortedGoodsList = computed(() => {
  const list = [...goodsList.value]
  
  switch (sortBy.value) {
    case 'sales':
      return list.sort((a, b) => b.payNums - a.payNums)
    case 'price-asc':
      return list.sort((a, b) => a.price - b.price)
    case 'price-desc':
      return list.sort((a, b) => b.price - a.price)
    default:
      return list
  }
})

// 加载分类列表
const loadCategories = async () => {
  try {
    const data = await getAllCategories()
    categories.value = data || []
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 加载搜索结果
const loadSearchResults = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      ...searchParams.value
    }

    // 移除空值参数
    Object.keys(params).forEach(key => {
      if (params[key] === null || params[key] === undefined || params[key] === '') {
        delete params[key]
      }
    })

    console.log('搜索参数:', params)

    const data = await searchGoods(params)
    goodsList.value = data.list || []
    total.value = data.total || 0
  } catch (error) {
    console.error('搜索失败:', error)
    ElMessage.error('搜索失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 分类筛选
const handleCategoryChange = (categoryId) => {
  searchParams.value.categoryId = categoryId
  pageNum.value = 1
  loadSearchResults()
}

// 价格筛选
const handlePriceFilter = () => {
  searchParams.value.minPrice = priceRange.value.min
  searchParams.value.maxPrice = priceRange.value.max
  pageNum.value = 1
  loadSearchResults()
}

// 重置价格
const handlePriceReset = () => {
  priceRange.value.min = null
  priceRange.value.max = null
  searchParams.value.minPrice = null
  searchParams.value.maxPrice = null
  pageNum.value = 1
  loadSearchResults()
}

// 排序
const handleSort = (type) => {
  sortBy.value = type
}

// 跳转到商品详情
const goToDetail = (goodsId) => {
  router.push(`/goods/${goodsId}`)
}

// 回到首页
const goToHome = () => {
  router.push('/')
}

// 获取图片URL
const getImageUrl = (imagePath) => {
  return getFileUrl(imagePath)
}

// 监听路由变化
watch(() => route.query, (newQuery) => {
  if (newQuery.keyword !== searchParams.value.goodsName) {
    searchParams.value.goodsName = newQuery.keyword || ''
    searchParams.value.categoryId = null
    searchParams.value.minPrice = null
    searchParams.value.maxPrice = null
    priceRange.value.min = null
    priceRange.value.max = null
    sortBy.value = 'default'
    pageNum.value = 1
    loadSearchResults()
  }
}, { immediate: true })

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.search-page {
  width: 100%;
  min-height: 100vh;
  background-color: #f5f5f5;
  margin: 0;
  padding: 0;
}

.container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.breadcrumb {
  margin-bottom: 20px;
  padding-top: 20px;
}

.content {
  background: white;
  border-radius: 8px;
  padding: 20px;
}

.search-conditions {
  margin-bottom: 30px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.search-header h3 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.result-count {
  font-size: 14px;
  color: #999;
}

.filters {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.filter-item {
  display: flex;
  align-items: flex-start;
  gap: 10px;
}

.filter-item label {
  min-width: 60px;
  font-size: 14px;
  font-weight: 500;
  color: #666;
  line-height: 32px;
}

.filter-options {
  flex: 1;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.filter-tag {
  cursor: pointer;
  transition: all 0.3s;
}

.filter-tag:hover {
  opacity: 0.8;
  transform: translateY(-2px);
}

.price-filter {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap;
}

.price-separator {
  color: #999;
}

.goods-list {
  min-height: 400px;
}

.goods-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.goods-card {
  cursor: pointer;
  transition: all 0.3s;
  border-radius: 8px;
  overflow: hidden;
}

.goods-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.goods-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
}

.goods-info {
  padding: 15px;
}

.goods-name {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin: 0 0 10px 0;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.goods-stats {
  display: flex;
  gap: 15px;
  margin-bottom: 10px;
  font-size: 13px;
  color: #999;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.goods-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 10px;
  border-top: 1px solid #f0f0f0;
}

.goods-price {
  font-size: 20px;
  font-weight: bold;
  color: #ff4d4f;
}

.goods-stock {
  font-size: 13px;
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}

@media (max-width: 768px) {
  .search-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }

  .filter-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .filter-item label {
    line-height: 1.5;
  }

  .goods-grid {
    grid-template-columns: repeat(auto-fill, minmax(160px, 1fr));
    gap: 15px;
  }

  .goods-image {
    height: 150px;
  }
}
</style>
